﻿<template>
  <div id="managementcompanyQuery">
    <div id="querys">
      <el-form inline>
        <el-form-item>
          <label for="import"> 批量导入 </label>
          <input
            type="file"
            id="import"
            @change="handleImport"
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          />
        </el-form-item>
        <el-form-item v-if="uploadShow">
          <el-button type="primary" @click="loads()" size="small"
            >上传</el-button
          >
        </el-form-item>
        <el-form-item v-if="!flage">
          <el-button type="primary" @click="outExecl(1)" size="small"
            >导出模板</el-button
          >
        </el-form-item>
      </el-form>
      <el-card class="box-card">
        <el-table :data="tables" max-height="440" style="width: 100%;" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="45px" v-if="execl.selectSign"></el-table-column>
          <el-table-column label="序号" width="62px" type="index"></el-table-column>
          <el-table-column v-for="item in execl.head" :key="item.field" :label="item.name" :prop="item.field" align="center" sortable show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{scope.row[item.field]}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
/* eslint-disable */

/*
使用方式
execlData: {
  title:"供应商资料",                                               【导出模板的文件名称】
  url:"/WP/ArticleManagement/StoreLeaseVendor/leaseVendorImpor",    【接口url】
  type:"POSJSON",                                                   【目前单一类型POSTJSON】
  head:[{                                                           【表头 required=true不为空，=false允许空】
    name: "供应商名称",
    field: "vendorName",
    required:true,
    max:20                                                          【表头 max为字段长度】
    }, {
    name: "供应商全称",
    field: "vendorFullName"
  }]
}
<en-query v-if="execl" ref="execl" :execl="execlData" @execlReturn="execlReturn"></en-query> 【调用格式】
                                                                                             【execlReturn为回调方法，导入成功后执行参数为200】

*/
import Blob from "@/components/Excel/Blob";
import Export2Excel from "@/components/Excel/Export2Excel";
export default {
  name: "managementcompanyQuery",
  components: {},
  data() {
    return {
      rules: {
        note: [
          {
            required: true,
            message: "请选择供应商分类",
            trigger: "blur",
          },
        ],
      },
      dialogFormVisible: false,
      diaLogTitle: "新增",
      tableDetail: "",
      returnList: [],
      excelData: [],
      tables: [], //表格内容
      selectArr:[],
      loading: false,

    };
  },
  props: ["execl", "uploadShow", "storeId", "flage"],
  created() {},
  methods: {
     handleSelectionChange(val){
      this.selectArr = val;
      this.$emit("update:selectArray",this.selectArr)
    },
    // 清除文件路径
    clearFile() {
      let obj = document.getElementById("import");
      obj.value = "";
    },
    //数据效验
    checkdata() {
      for (let i = 0; i < this.execl.head.length; i++) {
        //效验是否为空
        if (this.execl.head[i].required) {
          for (let index = 0; index < this.tables.length; index++) {
           
            if (!this.tables[index][this.execl.head[i].field] ) {
              this.$alert(this.execl.head[i].name +
                  "【第" +
                  parseInt(index + 1) +
                  "行】不可以为空,请补充后重新导入","提示",{
                    confirmButtonText: "确定",
                  });
              this.clearFile()
              return false;
            }
          }
        }
        //效验字段长度
        if (this.execl.head[i].max != undefined && this.execl.head[i].max > 0) {
          for (let index = 0; index < this.tables.length; index++) {
            if (
              this.tables[index][this.execl.head[i].field] == undefined ||
              this.tables[index][this.execl.head[i].field] == null || this.tables[index][this.execl.head[i].field] == ''
            ) {
              continue;
            } else {
              if (
                this.tables[index][this.execl.head[i].field].toString().length >
                this.execl.head[i].max
              ) {
                this.$message({
                  type: "error",
                  message:
                    this.execl.head[i].name +
                    "【第" +
                    parseInt(index + 1) +
                    "行】长度不可以超过" +
                    this.execl.head[i].max,
                });
                return false;
              }
            }
          }
        }
      }
      return true;
    },
    //异步效验数据有效性
    async loads() {
      let bool = await this.checkdata();
      if (!bool) {
        return;
      }
      let params = {
        storeId: this.storeId,
        opr: this.$session.GET("user"),
        file: this.tables,
        importDataList: this.tables,
      };
      this.$http.POSTJSON(this.execl.url, params).then((data) => {
        if (data.code == 200) {
          for (let index = 0; index < data.data.length; index++) {
            if (data.data[index].errorInfo != null) {
              this.$message({
                type: "error",
                message: "导入失败!",
              });
              this.returnList = data.data;
              this.outExecl(0);
              // let element = document.createElement('a')
              // element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data.data)))
              // element.setAttribute('download',"导入失败")
              // element.style.display = 'none'
              // element.click()
              return;
            }
          }
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.$emit("execlReturn"); //导入成功触发
        } else {
          this.$message({
            type: "error",
            message: "导入失败,请检查网络!",
          });
        }
      });
    },
    //导出模板
    outExecl(row) {
      let excelData = [];
      let Header = [];
      let filter = [];
      let title = this.execl.title;
      let data = [] //默认值
      this.execl.head.map((item) => {
        Header.push(item.name);
      });
      this.execl.head.map((item) => {
        filter.push(item.field);
      });
      this.execl.head.map((item) => {
        excelData.push(item.val);
      });
      if (row == 0) {
        excelData = this.returnList;
        Header.push("错误原因");
        filter.push("errorInfo");
        title = this.execl.title + "__导入失败";
      }
      require.ensure([], () => {
        const {
          export_json_to_excel,
        } = require("@/components/Excel/Export2Excel");
        const tHeader = Header; // 导出的表头名
        const filterVal = filter; // 导出的表头字段名
        // const list = excelData;
        // const data = list.map((v) => filterVal.map((j) => v[j]));
        data.push(excelData)
        console.log(filterVal,tHeader,data,title)
        export_json_to_excel(tHeader, data, title);
      });
    },
    //选择execl后生成data
    handleImport(event) {
      this.tables = [];
      // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件（或原始数据缓冲区）的内容
      let fileReader = new FileReader();
      var file = event.currentTarget.files[0];
      // 回调函数
      fileReader.onload = (ev) => {
        try {
          let data = ev.target.result;
          let workbook = XLSX.read(data, {
            type: "binary",
            // cellDates: true,//为true时 转为 日期格式 但缺 47秒
          });
          // excel读取出的数据
          let excelData = XLSX.utils.sheet_to_json(
            workbook.Sheets[workbook.SheetNames[0]]
          );
          // 将上面数据转换成 table需要的数据
          let arr = [];
          excelData.forEach((item) => {
            let obj = {};
            for (let i = 0; i < this.execl.head.length; i++) {
              for (let key in item) {
                if (this.execl.head[i].name == key) {
                  obj[this.execl.head[i].field] = item[key];
                  if (this.execl.head[i].type == "date") {
                    //如果是日期 转为日期格式
                     obj[this.execl.head[i].field] = this.formatDate(item[key],"-") //使用'-'拼接
                  }
                }
              }
            }
            arr.push(obj);
          });
            this.tables = [...arr];
            if(this.checkdata()){
              this.$emit("update:tables", this.tables)
            }
        } catch (e) {
          window.alert("文件类型不正确！");
          return false;
        }
      };
      // 读取文件 成功后执行上面的回调函数
      fileReader.readAsBinaryString(file);
    },
    formatDate(numb, format) {
      if(!numb){
        return ""
      }
      const time = new Date((numb - 1) * 24 * 3600000 + 1);
      time.setYear(time.getFullYear() - 70);
      const year = time.getFullYear() + "";
      const month = time.getMonth() + 1 + "";
      const date = time.getDate() - 1 + "";
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? "0" + month : month) +
          format +
          (date < 10 ? "0" + date : date)
        );
      }
      return (
        year +
        (month < 10 ? "0" + month : month) +
        (date < 10 ? "0" + date : date)
      );
    },
  },
};
</script>

<style scoped>
#querys {
  box-sizing: border-box;
  padding: 10px;
}
</style>